<?php



namespace Home\Controller;



use Think\Controller;



class TestController extends Controller {
	private $access_token='';
	public function abc() {

		// 设置选项，包括URL

		$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . appid . "&redirect_uri=http://nuower.com/index.php/Test/oauth&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";

		header("Location:".$url);

	}

	public function oauth() {

		if (isset ( $_GET ['code'] )) {

			$code = $_GET ['code'];

			$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . appid . "&secret=" . appsecret . "&code=" . $code . "&grant_type=authorization_code";

			$output = https_request ( $url );

			// 第二步

			if (isset ( $output )) {

				$jsoninfo = json_decode ( $output, true );
				session(array('expire'=>$jsoninfo['expires_in']));
				session('token',$jsoninfo['access_token']);
				$url_info = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $jsoninfo ['access_token'] . "&openid=" . appid . "&lang=zh_CN";

				$userInfo = https_request ( $url_info );

			} else {

				$this->error ( "不好意思,出错了" );

			}

			// 第三步

			if (isset ( $userInfo )) {

				$res = json_decode ( $userInfo, true );

				session ( "openid", $res ['openid'] );

				session ( "nickname", $res ['nickname'] );

				$this->display ( "Test/second" );

			} else {

				$this->error ( "不好意思,出错了" );

			}

		} else {

			$this->error ( "不好意思,出错了" );

		}

	}

	public function second() {
		//$this->display ( "second" );exit();
		$data = F ( 'data' );

		if (empty ( $data )) {

			$data = M ( 'swf_area' )->select ();

			$cache = F ( 'data', $data );

			$this->assign ( "city", $cache );

		} else {

			$this->assign ( "city", $data );

		}

		$this->display ( "second" );

	}
	
	
	
	public function third() {
		header ( "Content-type: text/html; charset=utf-8" );
		$data = I ();
		$jiaju = $data ['jiaju'];
		
		$jiajudata = explode('、',$jiaju);
		for ($i=0;$i<count($jiajudata)-1;$i++){ 
			$tmp=explode(' ', $jiajudata[$i]);
			$list[] = array(
				'name'=>$tmp[0],
				'num'=>$tmp[1],
			);
		}
		
		if(!empty($_REQUEST['shighdianti'])){  
			$startAdd=$data['startAdd']."有电梯";
		}else{
			$startAdd=$data['startAdd'].$data['shigh']."楼";	
		}
		
		if(!empty($_REQUEST['ehighdianti'])){  
			$endAdd=$data['endAdd']."有电梯";
		}else{
			$endAdd=$data['endAdd'].$data['ehigh']."楼";	
		}
		
		$this->assign ( "list", $list);
		$this->assign ( "jiaju", $data ['jiaju']);
		$this->assign ( "items", $jiaju);
		
		$this->assign ( "name", $data ['name']);
		$this->assign ( "mphone", $data ['mphone'] );
		$this->assign ( "appDate", $data ['appDate']);
		$this->assign ( "startAdd", $startAdd );
		$this->assign ( "endAdd", $endAdd );
		$this->assign ( "beizhu", $data['beizhu'] );
		$this->display ( "third" );

	}
	

	// 订单 需要搬运
	public function orders() {

		header ( "Content-type: text/html; charset=utf-8" );

		// 解释下参数: 参数1---目标邮箱, 参数2----邮件标题,参数三--邮件正文,参数四---发件人名称;

		$data = I ();

		$data ['orderno'] = $this->ordersNum ();

		$data ['ctime'] = date ( 'Y-m-d H:i:s' );

		$data ['openid'] = $_SESSION ['openid'];
		$otherimages=session('up_imgs');
		if ($otherimages) {
			$data ['otherimages'] =$otherimages;
		}

		session("name",$data ['name']);

		session("orderno",$data ['orderno']);

		unset ( $data ['options'] );

		unset ( $data ['costFb'] );

		$data ['time'] = $data ['appDate'] . $data ['appTime'];

		$appTime = $data ['appTime'];

		$appDate = $data ['appDate'];

		$shigh =  $data ['shigh'];

		$ehigh=  $data ['ehigh'];
		
		//$data['items'].="行李数".$data['count-input']."件<br/>大件家具：".$data['jiaju']."<br/>其他家居：".$data['ben'];

		unset ( $data ['ben'] );

		unset ( $data ['appTime'] );

		unset ( $data ['appDate'] );

		unset ( $data ['shigh'] );

		unset ( $data ['ehigh'] );

		$res = M ( 'order_p' )->add ($data);

		if ($res) {
			session('p_addid',$res);
	$this->sendtpl_msg('oB_KewRQprjKA4ETYbqcRQgMiBk0',$res,'专业搬家订单已提交');
	//$this->sendtpl_msg('oB_KewXjx0kMThvx12moge3K9n8k',$res,'专业搬家订单已提交');
	$this->success('提交成功。等待反馈',U('Test/abc'));
	//$this->redirect('abc');
			$tpl = "订购单号:<span style='color:red'>" . $data ['orderno'] . "</span><br>下单时间:<span style='color:red'>" . $data ['ctime'] . "</span><br>收到来自<span style='color:red'>" . $data ["getCity"] . "</span>的订单。总金额为:<span style='color:red'>" . $data ['cost'] . "</span><br>" . "联系人:<span style='color:red'>" . $data ['name'] . "</span><br>联系电话:<span style='color:red'>" . $data ['mphone'] . "</span><br>选择车型:<span style='color:red'>" . $data ['car'] . "</span><br>" . "搬家时间:<br><span style='color:red'>" . $appDate. " " . $appTime . "</span><br>" . "起始地：<br><span style='color:red'>" . $data ['startAdd'].$shigh . "楼</span><br>目的地：<br><span style='color:red'>" . $data ['endAdd'].$ehigh . "楼</span><br>搬运物品：<span style='color:red'>".$data ['items']."</span>";
				echo "1";
			/*if (SendMail ( 'wxd12777@163.com', '亲，又来新订单了！！', $tpl )) {

					

			} else {

				$this->error ( '订单失败了！' );

			}*/

			//$this->assign ( "tpl", $tpl );

			//$this->display ( "detail" );

		} else {

			$this->error ( "订单失败了1！" );

		}

		

	}

		//发送模板消息
	public function sendtpl_msg($touser='',$id='',$first=''){

$data = json_decode(get_php_file("access_token.php"));
if ($data->expire_time < time()) {
       $json_token=http_request("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".appid."&secret=".appsecret);
$access_token=json_decode($json_token,true);
//获得access_token
$this->access_token=$access_token['access_token'];
      if ($this->access_token) {
        $data->expire_time = time() + 7000;
        $data->access_token = $this->access_token;
        set_php_file("access_token.php", json_encode($data));
      }
    } else {
    	$data_token=$data->access_token;
     $this->access_token =$data_token;
    }
	$orderinfo=M('order_p')->find($id);
	$orderno=$orderinfo['orderno'];
	$cost=$orderinfo['cost'];
//模板消息	
$template=array(
'touser'=>$touser,
'template_id'=>"85vh2nUY5d0pGOYKdnqnY3_AjIWf8PO9c-RZSCWORUM",
'url'=>"http://nuower.com/index.php/test/showadmin/id/".$id,
'topcolor'=>"#7B68EE",
'data'=>array(
'first'=>array('value'=>urlencode($first),'color'=>"#743A3A"),
'keyword1'=>array('value'=>urlencode($orderinfo['name']),'color'=>'#743A3A'),
'keyword2'=>array('value'=>urlencode($orderinfo['mphone']),'color'=>'#743A3A'),
'keyword3'=>array('value'=>urlencode('专业搬家家庭搬运'),'color'=>'#743A3A'),
'keyword4'=>array('value'=>urlencode($orderinfo['time']),'color'=>'#743A3A'),
'keyword5'=>array('value'=>urlencode($orderinfo['items']),'color'=>'#743A3A'),
'remark'=>array('value'=>urlencode('专业搬家订单'),'color'=>'#743A3A'),
)
);
//发送客服消息
$cus_user=$orderinfo['openid'];

switch ($orderinfo['upselect']) {
	case 1:
		$content='挪窝儿已收到您的具体搬家需求

我们会在一个小时内给您出具一份详细的书面报价方案，请耐心等待

查看或者取消订单请点击：我的>我的订单';
		break;
	case 2:
		$content='挪窝儿已收到您的具体搬家需求

请您尽快上传照片，照片上传后我们会在一个小时内给您出具一份详尽的书面报价方案

上传照片或者取消订单请点击：我的>我的订单 ';
		break;
	case 3:
		$content='挪窝儿已收到您的具体搬家需求

我们会在一个小时内给您出具一份预估的书面报价方案，最终执行费用根据现场实际情况确定，请耐心等待

查看或者取消订单请点击：我的>我的订单';
		break;
	
	default:
		# code...
		break;
}


$data = '{
        "touser":"'.$cus_user.'",
        "msgtype":"text",
        "text":
        {
             "content":"'.$content.'"
        }
    }';

$json_template=json_encode($template);

$url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$this->access_token;
$url2 = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$this->access_token;

$res=http_request($url,urldecode($json_template));
$res2=https_post($url2,urldecode($data));
}

	// 取消订单

	public function delOrder() {

		$data ['openid'] = $_SESSION ['openid'];

		$name = $_SESSION['name'];

		$ordNo = $_SESSION['orderno'];

		$tpl = $name."(".$_SESSION['nickname'].")"."取消订单了"."单号为:". $ordNo;

		 

		$where = array (

				"openid" => $data ['openid'] ,

				"orderno" => $ordNo

		);

		//0代表以删除订单

		$status['status'] = '0';

		$res = M ( 'orders' )->where ( $where )->save($status);; // 删除用户数据

		if ($res) {

			if (SendMail ( 'nuowoer@163.com', '亲，有人取消订单了！', $tpl )) {

				$this->success("取消订单成功！",U ( 'Show/index' ));

			} else {

				$this->error ( "取消订单失败",U ( 'Show/index' ) );

			}

		} else {

			$this->error ( "取消订单失败",U ( 'Show/index' ) );

		}

	}

	// 单号

	public function ordersNum() {

		$data = date ( 'Ymd' );

		$whe = "%" . $data . '%';

		$where ['orderno'] = array (

				'like',

				$whe

		);

		$res = M ( 'order_p' )->where ( $where )->order ( 'id desc' )->getField ( 'orderno' );

		// 如果存在

		if ($res) {

			$order = substr ( $res, - 4 ) + 1;

			$orderNo = 'P' . $data . sprintf ( "%04d", $order ); // 生成4位数，不足前面补0

		} else {

			// 否则单号就是0001

			$orderNo = 'P' . $data . "0001";

		}

		return $orderNo;

	}

	/**

	 * 需要搬运的算法

	 * $Fc车费

	 */

	public function banYun() {

		header ( "Content-type: text/html; charset=utf-8" );

		$dst = $_POST ['dst'];

		$Fb = $_POST ['fb'];

		// $domain = substr(strstr($dst, "分钟"),6);
        //$datastr = explode("公里",$dst);
		
		$res = substr ( $dst, 0, strlen ( $dst ) - 6 );

		$car = $_POST ['car'];

		// 调用计算车费函数

		$Fc = $this->carCost ( $res, $car );

		$F = $Fc+$Fb;

		echo $F.'|'.$Fc;

	}

	/**

	 * *

	 * 车费计算公式

	 * $res距离,$car车型

	 *

	 * *

	 */

	private function carCost($res, $car) {

		switch ($car) {

			case "面包车" :

				// 起步价

				$Fa = 35;

				if ($res > 5) {

					$cost = round(35 + ($res - 5) * 4);

				} else {

					$cost = 35;

				}

				break;

			case "小型平板货车" :

				// 起步价

				$Fa = 60;

				if ($res > 5) {

					$cost = round(60 + ($res - 5) * 5);

				} else {

					$cost = 60;

				}

				break;

			case "中型平板货车" :

				// 起步价

				$Fa = 80;

				if ($res > 5) {

					$cost = round(80 + ($res - 5) * 5);

				} else {

					$cost = 80;

				}

				break;

			case "中型厢式货车" :

				// 起步价

				$Fa = 100;

				if ($res > 5) {

					$cost = round(100 + ($res - 5) * 5);

				} else {

					$cost = 100;

				}

				break;

			default :

				// 起步价

				$Fa = 35;

				if ($res > 5) {

					$cost = round(35 + ($res - 5) * 4);

				} else {

					$cost = 35;

				}

				break;

		}

		return $cost;

	}


		public function showadmin()
{	
	$id=I('get.id');
	$data=M('order_p')->find($id);
	$jiaju=$data['items'];
	$jiajudata = explode('、',$jiaju);
		for ($i=0;$i<count($jiajudata)-1;$i++){ 
			$tmp=explode(' ', $jiajudata[$i]);
			$list[] = array(
				'name'=>$tmp[0],
				'num'=>$tmp[1],
			);
		}
	/*$tpl = "订购单号:<span style='color:red'>" . $data ['orderno'] . "</span><br>下单时间:<span style='color:red'>" . $data ['ctime'] . "</span><br>联系人:<span style='color:red'>" . $data ['name'] . "</span><br>联系电话:<span style='color:red'>" . $data ['mphone'] . "</span><br>起始地：<br><span style='color:red'>" . $data ['startadd'] . "</span><br>目的地：<br><span style='color:red'>" . $data ['endadd'] . "</span><br>搬家时间:<br><span style='color:red'>".$data ['time']."</span><br>物品详情：<span style='color:red'>".$data['items']."</span><br>备注：<span style='color:red'>".$data['beizhu'];
$this->assign('tpl',$tpl);*/
	$this->assign('orderinfo',$data);
	$this->assign ( "list", $list);
	$this->display();
}

public function saveorder()
	{
		$orderid=I('get.id');
		$map['id']=$orderid;
		$save['paystatus']=1;
		$save['paytype']='wx';
		$q=M('order_p')->where($map)->save($save);
		$this->sendtpl_msg('oB_KewRQprjKA4ETYbqcRQgMiBk0',$orderid,'专业搬家订单已支付');
		//$this->sendtpl_msg('oB_KewXjx0kMThvx12moge3K9n8k',$orderid,'专业搬家订单已支付');
		if ($q) {
			$this->redirect('demo');
		}
	}

	public function uploadpic()
	{	
			$up_imgs=session('up_imgs');
			if ($up_imgs) {
					 $otherimages=json_decode($up_imgs,true); 
			}

		 $this->assign('otherimages',$otherimages);
		$this->display();
	}


	 private function get_php_file($filename) {
    return trim(substr(file_get_contents($filename), 15));
  }
  private function set_php_file($filename, $content) {
    $fp = fopen($filename, "w");
    fwrite($fp, "<?php exit();?>" . $content);
    fclose($fp);
  }

  public function upweixinpic()
  {	
  	$otherimages=I('otherimages');
  	$data = json_decode($this->get_php_file("access_token.php"));
if ($data->expire_time < time()) {
       $json_token=http_request("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".appid."&secret=".appsecret);
$access_token=json_decode($json_token,true);
//获得access_token
$this->access_token=$access_token['access_token'];
      if ($this->access_token) {
        $data->expire_time = time() + 7000;
        $data->access_token = $this->access_token;
        $this->set_php_file("access_token.php", json_encode($data));
      }
    } else {
     $this->access_token = $data->access_token;
    }


//$list = explode(',',$list['otherimages']);
 foreach ($otherimages as $key => $value) {
                     		//根据微信JS接口上传了图片,会返回上面写的images.serverId（即media_id），填在下面即可 
   $str = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=".$this->access_token."&media_id=".$value;       		 
 //获取微信“获取临时素材”接口返回来的内容（即刚上传的图片）  
 $a = file_get_contents($str);  
//$ext=substr(strrchr($a, '.'), 1);

//__DIR__指向当前执行的PHP脚本所在的目录 
$tmp_str= uniqid();
$return_array[]=$tmp_str;
$filenam='weixin/'.$tmp_str.'.jpg';
 //以读写方式打开一个文件，若没有，则自动创建  
 $resource = fopen('./Uploads/'.$filenam , 'w+');  
 //将图片内容写入上述新建的文件  
 fwrite($resource, $a);  
 //关闭资源  
 fclose($resource); 

           }
           $orderid=session('p_addid');
		$map['id']=$orderid;
		$f=M('order_p')->where($map)->find();
		if ($f['otherimages']) {
			$arr=unserialize($f['otherimages']);
			$return_array=array_merge($return_array,$arr);
		}
		$save['otherimages']=serialize($return_array);
		$q=M('order_p')->where($map)->save($save);
  
  }


}



?>